import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
import { SyncElement, toSharedType } from '@/slate-yjs';
import { useEffect, useMemo } from 'react';
import randomColor from 'randomcolor';
import { YArray } from 'yjs/dist/src/types/YArray';

import { REMOTE_WEBSOCKET_ENDPOINT } from '../share';

export function useWebSocket(slug: string, onOnlineStatusChange: (online: boolean) => void): [YArray<SyncElement>, WebsocketProvider] {
  const [sharedType, provider] = useMemo(() => {
    const doc = new Y.Doc();

    const sharedType = doc.getArray<SyncElement>('content');

    const provider = new WebsocketProvider(REMOTE_WEBSOCKET_ENDPOINT, slug, doc, {
      connect: true,
    });

    return [sharedType, provider];
  }, []);

  const color = useMemo(
    () =>
      randomColor({
        luminosity: 'dark',
        format: 'rgba',
        alpha: 1,
      }),
    [],
  );

  useEffect(() => {
    provider.on('status', ({ status }: { status: string }) => {
      onOnlineStatusChange(status === 'connected');
    });

    provider.awareness.setLocalState({
      alphaColor: color.slice(0, -2) + '0.2)',
      color,
    });

    // TODO 从服务器获取文本初始值
    provider.on('sync', (isSynced: boolean) => {
      if (isSynced && sharedType.length === 0) {
        toSharedType(sharedType, [{ type: 'paragraph', children: [{ text: 'Hello world!' }] }]);
      }
    });

    provider.connect();

    return () => {
      provider.disconnect();
    };
  }, [provider]);

  return [sharedType, provider];
}

function testSlateYjs(sharedType: Y.Array<SyncElement>) {
  // 模拟服务器数据
  setTimeout(() => {
    toSharedType(sharedType, [{ type: 'paragraph', children: [{ text: 'Hello world!' }] }]);
  }, 5000);
}
